<?php

namespace app\service\admin\system;

use app\model\Common;
use app\tools\WxPlatform;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Model;

class MyInfoService
{

    /**
     * 更新我的信息
     * @param array $request
     * @return int
     * @throws DbException
     */
    public static function updateData(array $request): int
    {
        $id = session('manage_info')['id'];
        return Common::updateData(AdminTable, ['id' => $id], $request);
    }

    /**
     * 更新账号密码
     * @param array $request
     * @return int|string
     * @throws DbException
     */
    public static function updatePassword(array $request)
    {
        $userSData = session('manage_info');
        if (!password_verify($request['old_password'], $userSData['password'])) {
            return '当前密码错误';
        }
        $password = password_hash($request['password'], PASSWORD_BCRYPT);
        return Common::updateData(AdminTable, ['id' => $userSData['id']], ['password' => $password]);
    }

    /**
     * 获取绑定信息
     * @return array|Model|null
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public static function bindInfo()
    {
        $id = session('manage_info')['id'];
        return Common::getData(AdminTable, ['id' => $id], ['id', 'wx_openid']);
    }

    /**
     * 用户绑定
     * @return array|string
     * @throws DbException
     */
    public static function userBind()
    {
        $data = [
            'type' => 2,
            'admin_id' => session('manage_info')['id'],
        ];
        $id = Common::addData(AdminWxLogTable, $data, true);
        $qrData = WxPlatform::getWxtTicketUrl($id);
        if (!$qrData) {
            Common::updateData(AdminWxLogTable, ['status' => 5]);
            return '微信公众号配置错误！';
        }
        Common::updateData(AdminWxLogTable, ['id' => $id], ['ticket' => $qrData['ticket']]);
        return [
            'id' => $id,
            'url' => $qrData['url'],
        ];
    }

    /**
     * 绑定状态
     * @param array $request
     * @return array|false|Model|null
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function bindingStatus(array $request)
    {
        if (!isset($request['id']) || !$request['id']) {
            return false;
        }
        return Common::getData(AdminWxLogTable, ['id' => $request['id']], ['id', 'status']);
    }
}